home *** CD-ROM | disk | FTP | other *** search
/ Programmer Power Tools / Programmer Power Tools.iso / progjrn / pj_7_3a.arc / GETOPT.C < prev    next >
C/C++ Source or Header  |  1989-04-02  |  1KB  |  50 lines

  1.  
  2. #include <stdio.h>
  3. /*
  4.  * get option letter from argument vector
  5.  */
  6. int    opterr = 1,        /* useless, never set or used */
  7.     optind = 1,        /* index into parent argv vector */
  8.     optopt;            /* character checked for validity */
  9. char    *optarg;        /* argument associated with option */
  10. #define BADCH    (int)'?'
  11. #define EMSG    ""
  12. #define tell(s)    fputs(*nargv,stderr);fputs(s,stderr); \
  13.         fputc(optopt,stderr);fputc('\n',stderr);return(BADCH);
  14. int
  15. getopt(int nargc,char **nargv,char *ostr)
  16. {
  17.     static char    *place = EMSG;    /* option letter processing */
  18.     register char    *oli;        /* option letter list index */
  19. #ifdef USG
  20. #define index    strchr
  21. #endif
  22.     char    *index();
  23.     if(!*place) {            /* update scanning pointer */
  24.         if(optind >= nargc || *(place = nargv[optind]) != '-' || !*++place) return(EOF);
  25.         if (*place == '-') {    /* found "--" */
  26.             ++optind;
  27.             return(EOF);
  28.         }
  29.     }                /* option letter okay? */
  30.     if ((optopt = (int)*place++) == (int)':' || !(oli = index(ostr,optopt))) {
  31.         if(!*place) ++optind;
  32.         tell(": illegal option -- ");
  33.     }
  34.     if (*++oli != ':') {        /* don't need argument */
  35.         optarg = NULL;
  36.         if (!*place) ++optind;
  37.     }
  38.     else {                /* need an argument */
  39.         if (*place) optarg = place;    /* no white space */
  40.         else if (nargc <= ++optind) {    /* no arg */
  41.             place = EMSG;
  42.             tell(": option requires an argument -- ");
  43.         }
  44.          else optarg = nargv[optind];    /* white space */
  45.         place = EMSG;
  46.         ++optind;
  47.     }
  48.     return(optopt);            /* dump back option letter */
  49. }
  50.